import express from 'express';
import cors from 'cors';
const app = express();
const port = 8082;

// 中间件
app.use(cors());
app.use(express.json());

// 模拟数字人API响应
const mockResponses = {
  generateCall: {
    code: 200,
    message: "success",
    data: {
      ai_agent_instance_id: "mock-instance-" + Date.now(),
      channel_id: "mock-channel-" + Date.now(),
      ai_agent_user_id: "mock-agent-user-" + Date.now(),
      rtc_auth_token: "mock-rtc-token-" + Date.now(),
      request_id: "mock-request-" + Date.now(),
      agent_type: "AvatarAgent",
      video_url: "https://mock-digital-human-video.com/stream"
    }
  },
  
  describeInstance: {
    code: 200,
    message: "success",
    data: {
      call_log_url: "https://mock-log-url.com",
      runtime_config: JSON.stringify({
        voiceId: "zhixiaoxia",
        enableVoiceInterrupt: true
      }),
      status: "Running",
      template_config: JSON.stringify({
        agentType: "AvatarAgent",
        avatar: {
          backgroundColor: "#000000",
          width: 512,
          height: 512
        }
      }),
      user_data: "mock user data",
      request_id: "mock-request-" + Date.now()
    }
  },
  
  config: {
    code: 200,
    message: "success",
    data: {
      supportedAgentTypes: ["AvatarAgent", "VideoAgent", "VisionAgent"],
      supportedVoiceIds: ["zhixiaoxia", "zhichu", "zhimiao", "zhiyan"],
      defaultConfig: {
        agentType: "AvatarAgent",
        region: "cn-shanghai",
        voiceId: "zhixiaoxia",
        enableVoiceInterrupt: true,
        enablePushToTalk: false,
        sessionTimeout: 300
      },
      avatarConfig: {
        backgroundColor: "#000000",
        width: 512,
        height: 512
      }
    }
  },
  
  rtcToken: {
    code: 200,
    message: "success",
    data: {
      rtc_auth_token: "mock-rtc-token-" + Date.now(),
      timestamp: Math.floor(Date.now() / 1000),
      expire_time: Math.floor(Date.now() / 1000) + 24 * 60 * 60
    }
  }
};

// 数字人API路由
app.post('/api/v2/digital-human/generateCall', (req, res) => {
  console.log('Generate digital human call:', req.body);

  // 验证智能体ID - 支持数字人智能体ID
  const agentId = req.body.aiAgentId || req.body.agentId;
  const validAgentIds = [
    'f97e8f48f6e64b679a977fb01bc9e28f', // 数字人智能体ID
    '8ed6ed9e6c57469e889a1bc3651ac64b'  // 语音通话智能体ID
  ];

  if (!validAgentIds.includes(agentId)) {
    return res.json({
      code: 400,
      message: `The specified agentId "${agentId}" is not found.`,
      request_id: "mock-error-" + Date.now()
    });
  }

  console.log(`✅ 使用智能体ID: ${agentId}, 地区: ${req.body.region || 'cn-beijing'}`);

  setTimeout(() => {
    res.json(mockResponses.generateCall);
  }, 1000); // 模拟网络延迟
});

app.post('/api/v2/digital-human/generateAIAgentCall', (req, res) => {
  console.log('Generate AI agent call (compatibility):', req.body);
  setTimeout(() => {
    res.json(mockResponses.generateCall);
  }, 1000);
});

app.post('/api/v2/digital-human/describeInstance', (req, res) => {
  console.log('Describe digital human instance:', req.body);
  setTimeout(() => {
    res.json(mockResponses.describeInstance);
  }, 500);
});

app.post('/api/v2/digital-human/describeAIAgentInstance', (req, res) => {
  console.log('Describe AI agent instance (compatibility):', req.body);
  setTimeout(() => {
    res.json(mockResponses.describeInstance);
  }, 500);
});

app.post('/api/v2/digital-human/getRtcAuthToken', (req, res) => {
  console.log('Get RTC auth token:', req.body);
  res.json(mockResponses.rtcToken);
});

app.get('/api/v2/digital-human/config', (req, res) => {
  console.log('Get digital human config');
  res.json(mockResponses.config);
});

app.get('/api/v2/digital-human/health', (req, res) => {
  res.json({
    code: 200,
    message: "success",
    data: {
      status: "UP",
      service: "digital-human-mock",
      timestamp: Date.now()
    }
  });
});

// 错误处理
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).json({
    code: 500,
    message: "Internal server error",
    error: err.message
  });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({
    code: 404,
    message: "API not found",
    path: req.path
  });
});

// 启动服务器
app.listen(port, () => {
  console.log(`🚀 Digital Human Mock Server running at http://localhost:${port}`);
  console.log('📋 Available endpoints:');
  console.log('  POST /api/v2/digital-human/generateCall');
  console.log('  POST /api/v2/digital-human/generateAIAgentCall');
  console.log('  POST /api/v2/digital-human/describeInstance');
  console.log('  POST /api/v2/digital-human/describeAIAgentInstance');
  console.log('  POST /api/v2/digital-human/getRtcAuthToken');
  console.log('  GET  /api/v2/digital-human/config');
  console.log('  GET  /api/v2/digital-human/health');
});

export default app;
